// 蜂窝蜜造平台生成代码，此文件只生成一次，不需要添加到 .beeignore

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.controller.purchase.PurchasePlansDController;
import com.fowo.api.controller.purchase.dto.localInventory;
import com.fowo.api.controller.purchase.dto.skuSales;
import com.fowo.api.entity.*;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.model.purchase.order.PurchaseOrderItemVo;
import com.fowo.api.model.purchase.order.PurchaseOrderSearchParamPo;
import com.fowo.api.model.purchase.order.PurchaseOrderVo;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductItemVo;
import com.fowo.api.model.purchase.plans.PurchasePlansVo;
import com.fowo.api.model.supplier.track.log.SupplierTrackLogItemVo;
import com.fowo.api.model.supplier.track.log.SupplierTrackLogSearchParamPo;
import com.fowo.api.service.InventoryDetailOrderlistService;
import com.fowo.api.service.SalesDailyListService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.util.LocalDateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 采购订单 服务实现类
 */
@Service
public class PurchaseOrderServiceImpl extends PurchaseOrderBaseServiceImpl {
    //获取库存信息
    @Resource
    private InventoryRealServiceImpl inventoryRealService;
    @Resource
    private FBAInventoryServiceImpl fbaInventoryService;
    @Resource
    private ProductBaseServiceImpl productService;
    @Resource
    private ListingFatherServiceImpl listingFatherService;
    @Resource
    private InventoryDetailOrderlistServiceImpl inventoryDetailOrderlistService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private StockageInfoOrderServiceImpl stockageInfoOrderService;
    @Resource
    private SalesDailyListServiceImpl salesDailyListService;

    /**
     * 获取详情
     *
     * @param id 采购订单的主键
     */
    @DataActivity(action = SysDataActivityAction.View)
    @Override
    public PurchaseOrderVo getVoById(Long id) throws Exception {
        PurchaseOrderVo voById = super.getVoById(id);

        for (int i = 0; i < voById.getPurchaseOrde().size(); i++) {
//            if(voById.getAnStatus().equals("0")){
//                PurchaseOrderProductItemVo purchaseOrderProductItemVo = voById.getPurchaseOrde().get(i);
//                //获取本店库库存
//                InventoryReal shopInventory = getShopInventory(purchaseOrderProductItemVo, 1,voById.getWid());
//                //获取其他店铺库存
//                InventoryReal shopInventory1 =getShopInventory(purchaseOrderProductItemVo,2,voById.getWid());
//                //获取公共的库存
//                InventoryReal shopInventory2 =getShopInventory(purchaseOrderProductItemVo,3,voById.getWid());
//                purchaseOrderProductItemVo.setLocalShopInventory(shopInventory!=null?shopInventory.getStockQty():0);
//                purchaseOrderProductItemVo.setOtherShopInventory(shopInventory1!=null?shopInventory1.getStockQty():0);
//                purchaseOrderProductItemVo.setPublicInventory(shopInventory2!=null?shopInventory2.getStockQty():0);
//            }

        }
        return voById;
    }


    @DataActivity(action = SysDataActivityAction.Add)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(PurchaseOrderVo model) throws Exception {
        model.getPurchaseOrde().forEach(x -> {
            x.setQuantityReceive(x.getQuantityReceive() == null ? x.getApplicationNum() : x.getQuantityReceive());
            x.setQuantityReceived(x.getQuantityReceived() == null ? 0 : x.getQuantityReceived());
        });
        this.purchaseCreateAndUpdateHandler(model);
        Long aLong = super.create(model);
        return aLong;
    }


    @DataActivity(action = SysDataActivityAction.Modified)
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(PurchaseOrderVo model) throws Exception {
        this.purchaseCreateAndUpdateHandler(model);
        return super.update(model);
    }

    /**
     * 处理采购订单的创建和修改  20240410:待到货量，退货量，到货货值，退货金额
     *
     * @param model
     */
    private void purchaseCreateAndUpdateHandler(PurchaseOrderVo model) {
        model.getPurchaseOrde().forEach(x -> {
            if (x.getFnsku() != null && x.getLxFnsku() == null) {
                ListingFather byId = listingFatherService.getById(x.getFnsku());
                x.setFnskuFnsku(byId.getFnsku());
                x.setLxFnsku(byId.getFnsku());
            }
        });
        //待到货量
        Integer quantityReceiveSum = Convert.toInt(NumberUtil.add(model.getPurchaseOrde().stream().map(PurchaseOrderProductItemVo::getQuantityReceive).toArray(Integer[]::new)));
        //退货量
        Integer quantityReturnSum = Convert.toInt(NumberUtil.add(model.getPurchaseOrde().stream().map(PurchaseOrderProductItemVo::getQuantityReturn).toArray(Integer[]::new)));
        //到货货值
        BigDecimal receivedGoodsValuesSum = NumberUtil.add(model.getPurchaseOrde().stream().map(PurchaseOrderProductItemVo::getReceivedGoodsValues).toArray(BigDecimal[]::new));
        //退款金额
        BigDecimal returnMoneySum = NumberUtil.add(model.getPurchaseOrde().stream().map(PurchaseOrderProductItemVo::getReturnMoney).toArray(BigDecimal[]::new));

        model.setQuantityReceive(quantityReceiveSum);
        model.setQuantityReturn(quantityReturnSum);
        model.setReceivedGoodsValues(receivedGoodsValuesSum);
        model.setReturnMoney(returnMoneySum);
    }

    //查询fba库存
    public String getFbaInventory(Long shopId, Long productId, String fnSku) {
        Product byId = productService.getById(productId);
//        ListingFather byId1 = listingFatherService.getById(fnSku);
        if (shopId != null) {
            QueryWrapper<FBAInventory> queryWrapper = new QueryWrapper();
            queryWrapper.eq("sid", shopId);
            queryWrapper.eq("fnsku", fnSku);
            queryWrapper.eq("sku", byId.getSku());
            List<FBAInventory> list = fbaInventoryService.list(queryWrapper);
            return list.size() > 0 ? JSON.toJSONString(list.get(0)) : null;
        }
        return null;
    }

    //查询本地的库存和库龄
    public String getLocalInventory(Long shopId, Long productId, Long fnSku) {
        localInventory localInventory = new localInventory();
        Product byId = productService.getById(productId);
        ListingFather byId1 = listingFatherService.getById(fnSku);
        ShopInfo byId2 = shopInfoService.getById(shopId);


        //查本店铺的库存
        if (byId2 != null && byId2.getShopCode() != null) {
            QueryWrapper<InventoryDetailOrderlist> queryWrapper = new QueryWrapper();
            queryWrapper.select("sum(product_total) as  product_total");
            queryWrapper.eq("scode", byId2.getShopCode());
            queryWrapper.eq("fnsku", byId1.getFnsku());
            queryWrapper.eq("sku", byId.getSku());
            InventoryDetailOrderlist one = inventoryDetailOrderlistService.getOne(queryWrapper);
            localInventory.setLocalShopInventory(one != null ? Long.valueOf(one.getProductTotal()) : 0);
            //查询库龄
            if (one != null) {
                List<StockageInfoOrder> list = stockageInfoOrderService.list(Wrappers.<StockageInfoOrder>query().lambda().eq(StockageInfoOrder::getParentInventoryDetailOrderlist, one.getId()));
                localInventory.setDayList(list);
            }
        }


        //查其他店铺的库存
        QueryWrapper<InventoryDetailOrderlist> queryWrapper2 = new QueryWrapper();
        queryWrapper2.select("sum(product_total) as  product_total");
        if (byId2 != null) {
            queryWrapper2.ne("scode", byId2.getShopCode());
        }
        queryWrapper2.ne("scode", 0);
        queryWrapper2.eq("sku", byId.getSku());
        InventoryDetailOrderlist one1 = inventoryDetailOrderlistService.getOne(queryWrapper2);
        localInventory.setOtherShopInventory(one1 != null ? Long.valueOf(one1.getProductTotal()) : 0);
        //查公共的库存
        QueryWrapper<InventoryDetailOrderlist> queryWrapper3 = new QueryWrapper();
        queryWrapper3.select("sum(product_total) as  product_total");
        queryWrapper3.eq("scode", 0);
        queryWrapper3.eq("sku", byId.getSku());
        InventoryDetailOrderlist one2 = inventoryDetailOrderlistService.getOne(queryWrapper3);
        localInventory.setPublicInventory(one2 != null ? Long.valueOf(one2.getProductTotal()) : 0);

        //查本本地的库存
        QueryWrapper<InventoryDetailOrderlist> queryWrapper4 = new QueryWrapper();
        queryWrapper4.select("sum(product_total) as  product_total");
        queryWrapper4.eq("sku", byId.getSku());
        InventoryDetailOrderlist one3 = inventoryDetailOrderlistService.getOne(queryWrapper4);
        localInventory.setLocalTotalInventory(one3 != null ? Long.valueOf(one3.getProductTotal()) : 0);


        return JSON.toJSONString(localInventory);
    }


    //获取销量
    public String getSale(Long shopId, Long productId, Long fnSku) {
        Date dateNow = new Date();
        skuSales skuSales = new skuSales();
        Date date = LocalDateUtils.addDateDays(dateNow, -2);
        Date date9 = LocalDateUtils.addDateDays(dateNow, -9);
        Date date17 = LocalDateUtils.addDateDays(dateNow, -17);
        Date date32 = LocalDateUtils.addDateDays(dateNow, -32);
        Date date62 = LocalDateUtils.addDateDays(dateNow, -62);
        Date date92 = LocalDateUtils.addDateDays(dateNow, -92);
        Date date182 = LocalDateUtils.addDateDays(dateNow, -182);
        Long sale9 = getSale2(shopId, fnSku, date9, date);
        Long sale17 = getSale2(shopId, fnSku, date17, date);
        Long sale32 = getSale2(shopId, fnSku, date32, date);
        Long sale62 = getSale2(shopId, fnSku, date62, date);
        Long sale92 = getSale2(shopId, fnSku, date92, date);
        Long sale182 = getSale2(shopId, fnSku, date182, date);
        skuSales.setDay7(sale9);
        skuSales.setDay15(sale17);
        skuSales.setDay30(sale32);
        skuSales.setDay60(sale62);
        skuSales.setDay90(sale92);
        skuSales.setDay180(sale182);
        return JSON.toJSONString(skuSales);
    }

    public Long getSale2(Long shopId, Long fnSku, Date startDate, Date endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ShopInfo byId2 = shopInfoService.getById(shopId);
        if (byId2 == null) {
            return Long.valueOf(0);
        }
        ListingFather byId1 = listingFatherService.getById(fnSku);
        QueryWrapper<SalesDailyList> queryWrapper = new QueryWrapper();
        queryWrapper.select("sum(map_value) as  map_value");
        queryWrapper.eq("scode", byId2.getShopCode());
        queryWrapper.eq("asin", byId1.getAsin());
        queryWrapper.between("bb_data", sdf.format(startDate), sdf.format(endDate));
        SalesDailyList one = salesDailyListService.getOne(queryWrapper);
        return one != null ? one.getMapValue().longValue() : 0;
    }

    //全部
    @Override
    public Page<?> completePageWithChildSearch(
            PurchaseOrderSearchParamPo search
    ) {
        return adddata(super.completePageWithChildSearch(search));
    }

    //待提交
    @Override
    public Page<?> changesToBeCommittedPageWithChildSearch(
            PurchaseOrderSearchParamPo search
    ) {
        return adddata(super.changesToBeCommittedPageWithChildSearch(search));
    }

    //待审批
    @Override
    public Page<?> theApprovalIsPendingPageWithChildSearch(
            PurchaseOrderSearchParamPo search
    ) {
        return adddata(super.theApprovalIsPendingPageWithChildSearch(search));
    }

    //待下单
    @Override
    public Page<?> stagingReleaseOrderPartsPageWithChildSearch(
            PurchaseOrderSearchParamPo search
    ) {
        return adddata(super.stagingReleaseOrderPartsPageWithChildSearch(search));
    }

    //待到货
    @Override
    public Page<?> awaitingArrivalPageWithChildSearch(
            PurchaseOrderSearchParamPo search
    ) {
        return adddata(super.awaitingArrivalPageWithChildSearch(search));
    }

    //已完成completedPage-with-child
    @Override
    public Page<?> completedPageWithChildSearch(
            PurchaseOrderSearchParamPo search
    ) {
        return adddata(super.completedPageWithChildSearch(search));
    }

    Page<?> adddata(Page<?> page) {
        List<JSONObject> records = (List<JSONObject>) page.getRecords();
        for (int i = 0; i < records.size(); i++) {
            JSONObject jsonObject = records.get(i);
            SupplierTrackLogSearchParamPo search = new SupplierTrackLogSearchParamPo();
            search.setParentPurchaseOrder(jsonObject.getLong("id"));
            List<SupplierTrackLogItemVo> search1 = supplierTrackLogService.search(search);
            String jsonString = JSON.toJSONString(search1);
            jsonObject.put("progresslog", jsonString);
        }
        return page;
    }


    @DataActivity(
            action = SysDataActivityAction.Other,
            message = "%s执行了下单操作"
    )
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void placeAnOrder(Long id) throws Exception {
        SpringUtil.getBean(PurchasePlansDController.class).placeAnOrder2(id);
    }

}
